//
//  TopMenuSelectView.m
//  YYPopMenuView
//
//  Created by 蓓蕾 on 2021/8/24.
//

#import "TopMenuSelectView.h"
#import "LeftTableViewCell.h"
#import "RightTableViewCell.h"
#import "YYPopMentHeaderView.h"

@interface TopMenuSelectView ()<UITableViewDelegate, UITableViewDataSource>
{
    NSInteger _selectIndex;
    BOOL _isScrollDown;
}
@property (nonatomic, strong) NSMutableDictionary *selectItemDic;

@property (nonatomic, strong) NSArray *leftTitleArr;

@property (nonatomic, strong) NSArray *rightContentArr;
@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTableView;

@property (nonatomic, assign) CGRect resultRect;

@end

@implementation TopMenuSelectView

-(id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        NSLog(@"self.frame = %@",NSStringFromCGRect(frame));
        _resultRect = frame;
        _selectIndex = 0;
        _isScrollDown = YES;
        
        [self addSubview:self.leftTableView];
        [self addSubview:self.rightTableView];
    }
    return self;
}

-(void)setLeftTitleArr:(NSArray * _Nonnull)leftTitleArr withRightContentArr:(NSArray * _Nonnull)rightContentArr
{
//    _rightContentArr = rightContentArr;
    if (leftTitleArr.count != rightContentArr.count) {
        NSLog(@"数据初始化失败");
        return;
    }
    NSMutableArray *tempArr = [NSMutableArray new];
    
    
    
    for (NSInteger i = 0; i < leftTitleArr.count; ++i) {
        NSArray *objectArr = rightContentArr[i];
        NSString *sectionString = leftTitleArr[i];
        NSString *selectItem = [objectArr firstObject];
        NSMutableDictionary *resultDic = [NSMutableDictionary new];
        resultDic[@"section"] = sectionString;
        resultDic[@"content"] = selectItem;
        self.selectItemDic[sectionString] = resultDic;
        YYTopMenuModel *model = [YYTopMenuModel new];
        model.SectionString = sectionString;
        model.TagArr = objectArr;
        [tempArr addObject:model];
    }
    _leftTitleArr = leftTitleArr;
    _rightContentArr = [NSArray arrayWithArray:tempArr];
    
    
    
    [_leftTableView reloadData];
    [_rightTableView reloadData];
    
    [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
}

- (UITableView *)leftTableView
{
    if (!_leftTableView)
    {
//        _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kLeftTableViewWidth, CGRectGetHeight(self.bounds))];
        _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kLeftTableViewWidth, YYMenu_SCREEN_HEIGHT)];
//        _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kLeftTableViewWidth, 250)];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
//        _leftTableView.rowHeight = 55;
        _leftTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _leftTableView.tableFooterView = [UIView new];
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.separatorColor = [UIColor clearColor];
        _leftTableView.backgroundColor = YYTopMenuRgbColor(0xF1F1F1);
        [_leftTableView registerClass:[LeftTableViewCell class] forCellReuseIdentifier:kCellIdentifier_Left];
    }
    return _leftTableView;
}

- (UITableView *)rightTableView
{
    if (!_rightTableView)
    {
//        NSLog(@"CGRectGetHeight(self.bounds) = %lf",CGRectGetHeight(self.bounds));
//        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(kLeftTableViewWidth, 0, CGRectGetWidth(self.bounds) - kLeftTableViewWidth, CGRectGetHeight(self.bounds))];
        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(kLeftTableViewWidth, 0, CGRectGetWidth(self.bounds) - kLeftTableViewWidth, YYMenu_SCREEN_HEIGHT)];
//        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(kLeftTableViewWidth, 0, CGRectGetWidth(self.bounds) - kLeftTableViewWidth, 250)];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
//        _rightTableView.rowHeight = 80;
        _rightTableView.backgroundColor = YYTopMenuRgbColor(0xE2E2E2);
        _rightTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _rightTableView.showsVerticalScrollIndicator = NO;
        _rightTableView.separatorColor = [UIColor clearColor];
        _rightTableView.tableFooterView = [UIView new];
        [_rightTableView registerClass:[RightTableViewCell class] forCellReuseIdentifier:kCellIdentifier_Right];
        [_rightTableView registerClass:[YYPopMentHeaderView class] forHeaderFooterViewReuseIdentifier:@"YYPopMentHeaderView"];
    }
    return _rightTableView;
}

#pragma mark - TableView DataSource Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_leftTableView == tableView)
    {
        return 1;
    }
    else
    {
        return _rightContentArr.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_leftTableView == tableView)
    {
        return _leftTitleArr.count;
    }
    else
    {
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView) {
        return 30;
    }
    else
    {
        if (indexPath.row < _rightContentArr.count) {
            YYTopMenuModel *model = _rightContentArr[indexPath.row];
            if (model.CellHeight == 0) {
                RightTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Right];
                cell.leftMargin = _leftMargin;
                cell.itemLineCount = _itemLineCount;
                cell.itemWidth = _itemWidth;
                cell.topMargin = _topMargin;
                cell.bottomMargin = _bottomMargin;
                cell.itemHorizontalMargin = _itemHorizontalMargin;
                cell.itemVerticalMargin = _itemVerticalMargin;
                cell.itemHeight = _itemHeight;
                
                cell.autoSize = _autoSize;
                CGFloat cellHeight = [cell getCellHeight:model];
                return cellHeight;
            }
            else
            {
                return model.CellHeight;
            }
            return model.CellHeight;
        }
        return 1000;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_leftTableView == tableView)
    {
        LeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Left forIndexPath:indexPath];
        if (indexPath.row < _leftTitleArr.count) {
            NSString *text = _leftTitleArr[indexPath.row];
            cell.name.text = text;
        }
        
        return cell;
    }
    else
    {
        RightTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Right forIndexPath:indexPath];
        if (indexPath.row < _rightContentArr.count) {
            cell.leftMargin = _leftMargin;
            cell.itemLineCount = _itemLineCount;
            cell.itemWidth = _itemWidth;
            cell.topMargin = _topMargin;
            cell.bottomMargin = _bottomMargin;
            cell.itemHorizontalMargin = _itemHorizontalMargin;
            cell.itemVerticalMargin = _itemVerticalMargin;
            cell.itemHeight = _itemHeight;
            cell.autoSize = _autoSize;
            YYTopMenuModel *model = _rightContentArr[indexPath.section];
            cell.sectionString = model.SectionString;
            cell.model = model;
        }
        YYMenuWeakSelf
        cell.ItemBlock = ^(NSDictionary *selectDic) {
            NSLog(@"selectDic = %@",selectDic);
            NSString *key = selectDic[@"section"];
//            NSString *value = selectDic[@"content"];
            [weakSelf.selectItemDic removeObjectForKey:key];
            [weakSelf.selectItemDic setObject:selectDic forKey:key];
            NSLog(@"weakSelf.selectItemDic = %@",weakSelf.selectItemDic);
        };
        
        cell.SelectItemBlock = ^(NSInteger index) {
            if (weakSelf.SelectShaiXuanItemBlock) {
                weakSelf.SelectShaiXuanItemBlock(indexPath.section, index);
            }
        };
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_rightTableView == tableView)
    {
        return 20;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_rightTableView == tableView)
    {
        YYPopMentHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"YYPopMentHeaderView"];
        if (section < _leftTitleArr.count) {
            NSString *sectionString = _leftTitleArr[section];
            headerView.titleString = sectionString;
        }
        return headerView;
    }
    return nil;
}

// TableView分区标题即将展示
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向上，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((_rightTableView == tableView)
        && !_isScrollDown
        && (_rightTableView.dragging || _rightTableView.decelerating))
    {
        [self selectRowAtIndexPath:section];
    }
}

// TableView分区标题展示结束
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向下，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((_rightTableView == tableView)
        && _isScrollDown
        && (_rightTableView.dragging || _rightTableView.decelerating))
    {
        [self selectRowAtIndexPath:section + 1];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (_leftTableView == tableView)
    {
        _selectIndex = indexPath.row;
        [_rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_selectIndex] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        [_leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_selectIndex inSection:0]
                              atScrollPosition:UITableViewScrollPositionTop
                                      animated:YES];
    }
}

// 当拖动右边TableView的时候，处理左边TableView
- (void)selectRowAtIndexPath:(NSInteger)index
{
    [_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]
                                animated:YES
                          scrollPosition:UITableViewScrollPositionTop];
}

#pragma mark - UISrcollViewDelegate
// 标记一下RightTableView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static CGFloat lastOffsetY = 0;

    UITableView *tableView = (UITableView *) scrollView;
    if (_rightTableView == tableView)
    {
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

-(NSDictionary *)getSelectResult
{
    return self.selectItemDic;
}

-(void)selectShaiXuanItemWithLeftRow:(NSInteger)row withIndex:(NSInteger)index
{
    [self selectRowAtIndexPath:row];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:row];
    RightTableViewCell *cell = [_rightTableView cellForRowAtIndexPath:indexPath];
    
    NSArray *subArr = [cell.contentView subviews];
    NSLog(@"subArr.count = %ld",subArr.count);
    
    for (UIButton *btn in [cell.contentView subviews]) {
        if ([btn isKindOfClass:[UIButton class]]) {
            NSLog(@"btn.tag = %ld",btn.tag);
            if (btn.tag == index) {
                btn.selected = YES;
                btn.backgroundColor = SelectItemBgColor;
            }
            else
            {
                btn.selected = NO;
                btn.backgroundColor = NormalItemBgColor;
            }
        }
    }
}

-(void)show
{
    if (_showAnimation) {
        self.frame = CGRectMake(CGRectGetMinX(_resultRect), -CGRectGetHeight(_resultRect), CGRectGetWidth(_resultRect), CGRectGetHeight(_resultRect));
        YYMenuWeakSelf
        self.hidden = NO;
        self.alpha = 0;
        [UIView animateWithDuration:0.3 animations:^{
            self.alpha = 1;
            weakSelf.frame = weakSelf.resultRect;
        }];
    }
    else
    {
        self.hidden = NO;
    }
}

-(void)dismiss:(void(^)(NSDictionary *resultDic))result
{
    YYMenuWeakSelf
    if (result) {
        result(self.selectItemDic);
    }
    if (_showAnimation) {
        self.frame = weakSelf.resultRect;
        self.alpha = 1;
        [UIView animateWithDuration:0.3 animations:^{
            self.alpha = 0;
            weakSelf.frame = CGRectMake(CGRectGetMinX(weakSelf.resultRect), -CGRectGetHeight(weakSelf.resultRect), CGRectGetWidth(weakSelf.resultRect), CGRectGetHeight(weakSelf.resultRect));
        } completion:^(BOOL finished) {
            weakSelf.hidden = YES;
        }];
    }
    else
    {
        weakSelf.hidden = YES;
    }
    
}

-(NSMutableDictionary *)selectItemDic
{
    if (!_selectItemDic) {
        _selectItemDic = [NSMutableDictionary new];
    }
    return _selectItemDic;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
